package com.hrm.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.TimeUnit;

import static com.alibaba.druid.support.json.JSONUtils.toJSONString;

@Component
public class DuanxinUtils {
    private Client client;
    private static final int CODE_LENGTH = 6;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    public DuanxinUtils() throws Exception {
        this.client = createClient();
    }

    private Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));

        // 配置 Endpoint
        config.endpoint = "dysmsapi.aliyuncs.com";

        return new Client(config);
    }

    private String generateRandomCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder(CODE_LENGTH);
        for (int i = 0; i < CODE_LENGTH; i++) {
            code.append(random.nextInt(10)); // 生成 0-9 的随机数字
        }
        return code.toString();
    }

    public SendSmsResponse sendSms(String phoneNumber) throws Exception {
        String code = generateRandomCode(); // 生成随机验证码
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.set(phoneNumber, code, 10, TimeUnit.SECONDS);// 保存验证码到 Redis，有效期 5 分钟
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phoneNumber)
                .setSignName("农村便民服务")
                .setTemplateCode("SMS_473355202")
                .setTemplateParam("{\"code\":\"" + code + "\"}");

        // 获取响应对象
        return client.sendSms(sendSmsRequest);
    }

       /* public static void main(String[] args) {
            try {
                DuanxinUtils smsUtils = new DuanxinUtils();
                SendSmsResponse response = smsUtils.sendSms("19880966426", "农村便民服务", "SMS_473355202", "{\"code\":\"789789\"}");
                // 输出响应
                System.out.println(toJSONString(response));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }*/
}
